<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="/assets/css/element.css">
    <link rel="stylesheet" href="/assets/css/admin/test/add.css">
</head>

<body>
<div id="app">
    <el-steps :active="choose_step" simple>
        <el-step title="1、基础信息" icon=" "></el-step>
        <el-step title="2、规格/价格" icon=" "></el-step>
        <el-step title="3、商品详情" icon=" "></el-step>
    </el-steps>

    <!--    基础详情-->
    <div class="zn-goods_box" v-if="show_one_tab == 1">
        <div class="goods_input_box">
            <div class="goods_title" >商品标题：</div>
            <div style="width: 90%">
                <el-input
                        size="medium"
                        placeholder="请输入内容"
                        v-model="input"
                        clearable>
                </el-input>
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">商品状态：</div>
            <div>
                <el-radio-group v-model="radio">
                    <el-radio :label="3">上架</el-radio>
                    <el-radio :label="6">隐藏</el-radio>
                    <el-radio :label="9">下架</el-radio>
                </el-radio-group>
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">排序：</div>
            <el-input-number v-model="sortnum" size="small" controls-position="right" @change="handleChange" :min="1"></el-input-number>
            <div class="sort_text">排序的大小默认按照从大到小排列</div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">商品主图：</div>
            <div class="goods_img">
                <el-upload
                        class="avatar-uploader goods_img"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else  class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>
            <div class="sort_text">作用于商城列表、分享头图；建议尺寸：174*174像素</div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">轮播图：</div>
            <div class="goods_img">
                <el-upload
                        class="avatar-uploader goods_img"
                        action="https://jsonplaceholder.typicode.com/posts/"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else  class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">商品分类：</div>
            <div class="new_box_crae">
                <el-cascader :props="props"></el-cascader>
                <el-button class="new_crae" type="text" @click="create_page">新建分类</el-button>
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">虚增销量：</div>
            <div style="width: 90%">
                <el-input
                        size="medium"
                        placeholder="请输入内容"
                        v-model="input"
                        clearable>
                </el-input>
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">浏览人数：</div>
            <div style="width: 90%">
                <el-input
                        size="medium"
                        placeholder="请输入内容"
                        v-model="input"
                        clearable>
                </el-input>
            </div>
        </div>

    </div>

    <!--    规格/价格-->
    <div class="zn-goods_box" v-if="show_one_tab == 2">
        <div class="goods_input_box">
            <div class="goods_title">商品规格：</div>
            <div style="width: 90%">
                <el-radio v-model="radiog" @change="choose_guige_radiog" label="1">单规格</el-radio>
                <el-radio v-model="radiog" @change="choose_guige_radiog" label="2">多规格</el-radio>
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">售卖价格：</div>
            <div style="width: 40%">
                <el-input
                        size="medium"
                        placeholder="请输入内容"
                        v-model="input"
                        clearable>
                </el-input>
            </div>
            <div class="sort_text">商品没有优惠的情况下售卖的价格</div>
        </div>


        <div class="goods_input_box">
            <div class="goods_title">售卖价格：</div>
            <div style="width: 40%">
                <el-input size="medium" placeholder="请输入内容" >
                    <template slot="append">元</template>
                </el-input>
            </div>
            <div class="sort_text">划线价在商品列表及详情会以划线形式显示</div>
        </div>

        <div v-if="goodsDetail.is_sku == 0">
            <div class="goods_input_box">
                <div class="goods_title">商品库存：</div>
                <div style="width: 40%">
                    <el-input size="medium" placeholder="请输入内容" >
                        <template slot="append">个</template>
                    </el-input>
                </div>
            </div>

            <div class="goods_input_box">
                <div class="goods_title">商品重量：</div>
                <div style="width: 40%">
                    <el-input size="medium" placeholder="请输入内容" >
                    </el-input>
                </div>
            </div>

            <div class="goods_input_box">
                <div class="goods_title">商品编号：</div>
                <div style="width: 40%">
                    <el-input size="medium" placeholder="请输入内容" >

                    </el-input>
                </div>
            </div>
        </div>

        <div v-if="goodsDetail.is_sku==1">
            <div class="add-sku-box">
                <div class="" v-for="(s, k) in skuList">
                    <div class="display-flex sku-item" style="justify-content: space-between;">
                        <div class="display-flex">
                            <div>规格名称：</div>
                            <div style="width: 120px;">
                                <el-input type="input" v-model="skuList[k]['name']" maxlength="5"
                                          placeholder="请输入名称">
                                </el-input>
                            </div>
                        </div>

                        <div style="width: 20px;height: 20px;" @click="deleteMainSku(k)">
                            <img class="label-auto" src="/assets/addons/shopro/img/goods/close.png">
                        </div>
                    </div>
                    <div class="display-flex sku-item sku-item-level"
                         style="background: #fff;padding: 10px 20px;">
                        <div style="width: 60px;">规格值：</div>
                        <div class="display-flex sku-item sku-item-level2">
                            <div class="sku-children" v-for="(sc, c) in s.children">
                                <el-input type="input" v-model="skuList[k]['children'][c]['name']"
                                          placeholder="请输入规格值" maxlength="22">
                                </el-input>
                                <div class="display-flex sku-children-del" @click="deleteChildrenSku(k,c)">
                                    <img class="label-auto" src="/assets/addons/shopro/img/goods/close.png">
                                </div>
                            </div>
                            <span style="color: #7536D0;cursor: pointer;"
                                  @click="addChildrenSku(k)">添加</span>
                        </div>

                    </div>
                </div>
                <div class="display-flex sku-item">
                    <div class="btn-common add-level1-sku" @click="addMainSku">
                        <i class="el-icon-plus"></i>
                        <span>添加规格</span>
                    </div>
                </div>
            </div>

            <!--            第二部-->

            <el-form :model="goodsDetail"  ref="goodsDetail" label-width="100px" class="demo-goodsDetail">
                <div class="table-box" v-show="skuPrice.length && skuList.length">
                    <table class="table">
                        <thead>
                        <tr>
                            <template v-for="(item, i) in skuList" >
                                <th v-if="item.children.length">
                                    <span class="th-center">{{item.name}}</span>
                                </th>
                            </template>
                            <th width="60">图片</th>
                            <th width="90">
                                <div class="display-flex">
                                    <span>价格(元)</span>
                                    <el-popover placement="top" width="160" v-model="allEditPopover.price">
                                        <el-input v-model="allEditDatas" placeholder="请输入内容"></el-input>
                                        <div style="text-align: right; margin: 0">
                                            <el-button size="mini" type="text"
                                                       @click="allEditData('price','cancel')">取消</el-button>
                                            <el-button type="primary" size="mini"
                                                       @click="allEditData('price','define')">确定</el-button>
                                        </div>
                                        <div slot="reference">
                                            <img class="all-edit-img"
                                                 src="/assets/addons/shopro/img/goods/batch.png"></div>
                                    </el-popover>
                                </div>
                            </th>
                            <th width="90">
                                <div class="display-flex">
                                    <span>库存(个)</span>
                                    <el-popover placement="top" width="160" v-model="allEditPopover.stock">
                                        <el-input v-model="allEditDatas" placeholder="请输入内容"></el-input>
                                        <div style="text-align: right; margin: 0">
                                            <el-button size="mini" type="text"
                                                       @click="allEditData('stock','cancel')">取消</el-button>
                                            <el-button type="primary" size="mini"
                                                       @click="allEditData('stock','define')">确定</el-button>
                                        </div>
                                        <div slot="reference">
                                            <img class="all-edit-img"
                                                 src="/assets/addons/shopro/img/goods/batch.png"></div>
                                    </el-popover>
                                </div>
                            </th>
                            <th width="90">
                                <div class="display-flex">
                                    <span>重量</span>
                                    <el-popover placement="top" width="160" v-model="allEditPopover.weight">
                                        <el-input v-model="allEditDatas" placeholder="请输入内容"></el-input>
                                        <div style="text-align: right; margin: 0">
                                            <el-button size="mini" type="text"
                                                       @click="allEditData('weight','cancel')">取消</el-button>
                                            <el-button type="primary" size="mini"
                                                       @click="allEditData('weight','define')">确定</el-button>
                                        </div>
                                        <div slot="reference">
                                            <img class="all-edit-img"
                                                 src="/assets/addons/shopro/img/goods/batch.png"></div>
                                    </el-popover>
                                </div>
                            </th>
                            <th width="90">
                                <div class="display-flex">
                                    <span>编码</span>
                                    <el-popover placement="top" width="160" v-model="allEditPopover.sn">
                                        <el-input v-model="allEditDatas" placeholder="请输入内容"></el-input>
                                        <div style="text-align: right; margin: 0">
                                            <el-button size="mini" type="text"
                                                       @click="allEditData('sn','cancel')">取消</el-button>
                                            <el-button type="primary" size="mini"
                                                       @click="allEditData('sn','define')">确定</el-button>
                                        </div>
                                        <div slot="reference">
                                            <img class="all-edit-img"
                                                 src="/assets/addons/shopro/img/goods/batch.png"></div>
                                    </el-popover>
                                </div>
                            </th>
                            <th width="70">当前状态</th>
                        </tr>
                        </thead>
                        <tbody>
                        <tr v-for="(item, i) in skuPrice" :key="i">
                            <td v-for="(v, j) in item.goods_sku_text" :key="j">
                                <span class="th-center">{{v}}</span>
                            </td>
                            <td width="60">
                                <div class="display-flex table-upload-img">
                                    <div class="sku-img" v-if="item.image">
                                        <img :src="Fast.api.cdnurl(item.image)" class="label-auto">
                                        <i class="el-icon-close" @click="delImg('sku',i)"></i>
                                    </div>
                                    <div v-else @click="addImg('sku',i,false)">
                                        <i class="el-icon-plus" style="font-size:18px;"></i>
                                    </div>
                                </div>
                            </td>
                            <td width="90">
                                <el-input type="input" v-model="item.price"></el-input>
                            </td>
                            <td width="90">
                                <el-input type="input" v-model="item.stock"></el-input>
                            </td>
                            <td width="90">
                                <el-input type="input" v-model="item.weight"></el-input>
                            </td>
                            <td width="90">
                                <el-input type="input" v-model="item.sn"></el-input>
                            </td>
                            <td width="70"><span class="sku-status th-center"
                                                 @click="editStatus(i)">{{item.status=='up'?'上架':'下架'}}</span>
                            </td>
                        </tr>
                        </tbody>
                    </table>
                </div>
            </el-form>
        </div>


    </div>

    <!--    商品详情-->
    <div class="zn-goods_box" v-if="show_one_tab == 3">

        <div class="goods_input_box">
            <div class="goods_title">服务标签：</div>
                <el-select v-model="timeData.service_ids_arr" placeholder="请选择" multiple
                           @change="serviceChange" @focus="getServiceOptions">
                    <el-option v-for="item in serviceOptions" :key="item.value" :label="item.name"
                               :value="item.id">
                    </el-option>
                </el-select>

            <div class="create-template" @click="createTemplate('service')">
                新建标签
            </div>
        </div>

        <div class="goods_input_box">
            <div class="goods_title">服务标签：</div>
            <div class="goods-detail-table">
                <div class="display-flex goods-detail-item">
                    <div class="goods-detail-name">
                        参数名称
                    </div>
                    <div class="goods-detail-msg">
                        内容
                    </div>
                    <div class="goods-detail-del">
                        删除
                    </div>
                    <div class="goods-detail-move">
                        移动
                    </div>
                </div>
                <draggable :list="goodsDetail.params_arr" v-bind="$attrs" :options="{animation:500}">
                    <div class="display-flex goods-detail-item"
                         v-for="(it,index) in goodsDetail.params_arr">
                        <div class="goods-detail-name">
                            <el-input type="input" v-model="it.title" style="width:90px">
                            </el-input>
                        </div>
                        <div class="goods-detail-msg">
                            <el-input type="input" v-model="it.content" style="width:348px">
                            </el-input>
                        </div>
                        <div class="goods-detail-del">
                            <div class="goods-detail-del-icon" @click="delParams(index)">
                                删除
                            </div>
                        </div>
                        <div class="goods-detail-move">
                            <img src="/assets/addons/shopro/img/goods/move.png">
                        </div>
                    </div>
                </draggable>
            </div>
        </div>

        <div class="btn-common add-params" @click="addParams">
            <i class="el-icon-plus"></i>
            <span>添加参数</span>
        </div>


    </div>


    <div class="floor_button">
        <el-button size="medium" @click="goto_next" type="primary" >下一步</el-button>
    </div>


</div>
<form id="add-form" class="form-horizontal" role="form" data-toggle="validator" method="POST" action="">
    <div class="form-group">
        <label class="control-label col-xs-12 col-sm-2">{:__('图文详情')}:</label>
        <div class="col-xs-12 col-sm-8">
            <textarea id="c-content" class="form-control editor" rows="5" name="row[content]" cols="50"></textarea>
        </div>
    </div>
</form>
<!--    <textarea id="c-content" class="form-control editor" rows="5" name="row[content]" cols="50"></textarea>-->
</body>

<!-- import Vue before Element -->
<script src="/assets/js/vue/vue.js"></script>
<!-- import JavaScript -->
<script src="/assets/js/element/element.js"></script>
<script>
    let id = 0;
    new Vue({
        el: '#app',
        data: function() {
            return {
                show_one_tab: 1,
                choose_step: 1,
                visible: false,
                input: '',
                radio: 3,
                radiog: '1',
                sortnum: 1,
                imageUrl: '',
                is_sku: 1,
                //多规格
                skuList: [],
                skuModal: '',    //
                countId: 1, // 这是点了多少次规格组按钮
                childrenModal: [],
                skuPrice: [],
                skuListData: '',
                skuPriceData: '',

                goodsDetail: {},    // 商品详情
                goodsDetailInit:{   // 商品详情初始化
                    category_ids: '',
                    content: '',
                    dispatch_ids: '',

                    express_ids: '', //单个数组
                    store_ids: '',
                    selfetch_ids: '',
                    autosend_ids: '',

                    dispatch_type: '',
                    expire_day: 0, //有效时间
                    image: '',
                    images: '',
                    is_sku: 0,
                    original_price: '',
                    params: '',
                    params_arr: [],
                    price: '',
                    service_ids: '',
                    show_sales: '',
                    status: 'up',
                    subtitle: '',
                    title: '',
                    type: 'normal',
                    views: '',
                    weigh: '',
                    weight: '',
                    stock: '',
                    sn: '',
                    autosend_content: ''
                },
                timeData: {
                    images_arr: [],
                    category_ids_arr: [],
                    dispatch_type_arr: [], //类型
                    dispatch_ids_arr: [], //id数组
                    service_ids_arr: [], //服务
                },
                // 服务
                serviceOptions: [],
                dispatchType: [],
                dispatchOptions: {},
                allEditPopover: {
                    price: false,
                    stock: false,
                    weight: false,
                    sn: false,
                },
                stepActive: 1,
                allEditDatas: "",
                props: {
                    lazy: true,
                    lazyLoad(node, resolve) {
                        const {level} = node;
                        setTimeout(() => {
                            const nodes = Array.from({length: level + 1})
                                .map(item => ({
                                    value: ++id,
                                    label: `选项${id}`,
                                    leaf: level >= 2
                                }));
                            // 通过调用resolve将子节点数据返回，通知组件数据加载完成
                            resolve(nodes);
                        }, 1000);
                    }
                },
            }
        },
        created(){
            this.goodsDetail = JSON.parse(JSON.stringify(this.goodsDetailInit));
            this.getInit([], [])
        },
        methods: {
            guigi(){
                console.log(this.skuList);
            },
            create_page(){
                console.log(12312);
                Fast.api.open('test/testhtml','2','')
            },
            handleChange(value) {
                console.log(value);
            },
            handleAvatarSuccess(res, file) {
                this.imageUrl = URL.createObjectURL(file.raw);

            },
            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 2MB!');
                }
                return isJPG && isLt2M;
            },
            // 下一步
            goto_next(){
                if(this.show_one_tab == 1){
                    this.show_one_tab = 2;
                    this.choose_step = 2;
                }else if(this.show_one_tab == 2){
                    this.show_one_tab = 3;
                }
            },
            //选择单规格还是多规格
            choose_guige_radiog($event){
                if($event == 1){  // $event == 1是单规格
                    // $event == 2是多规格
                    this.goodsDetail.radiog_guige = 1;
                    this.goodsDetail.is_sku = 0;
                }else if ($event == 2){
                    this.goodsDetail.radiog_guige = 2;
                    this.goodsDetail.is_sku = 1;
                }
            },
            handleClickss(tab) {
                this.activeIndex = Number(tab.index)
            },
            createCategory() {
                let that = this;
                Fast.api.open("shopro/category/add", "新建", {
                    callback(data) {
                        that.getCategoryOptions();
                    }
                });
            },
            panelChange(val) {
                let that = this;
                that.selectedcatArr = [];
                let nameArr = []
                let idsArr = []
                if (val.length > 0) {
                    val.forEach(j => {
                        let arr = []
                        if (j.length == 1) {
                            that.categoryOptions[that.activeIndex].children.forEach(c => {
                                if (c.id == j[0]) {
                                    arr.push(c.name)
                                }
                            })
                        } else if (j.length == 2) {
                            that.categoryOptions[that.activeIndex].children.forEach(c => {
                                if (c.id == j[0]) {
                                    arr.push(c.name)
                                    c.children.forEach(a => {
                                        if (a.id == j[1]) {
                                            arr.push(a.name)
                                        }
                                    })
                                }
                            })
                        } else if (j.length == 3) {
                            that.categoryOptions[that.activeIndex].children.forEach(c => {
                                if (c.id == j[0]) {
                                    arr.push(c.name)
                                    c.children.forEach(a => {
                                        if (a.id == j[1]) {
                                            arr.push(a.name)
                                            a.children.forEach(t => {
                                                if (t.id == j[2]) {
                                                    arr.push(t.name)
                                                }
                                            })
                                        }
                                    })
                                }
                            })
                        }
                        nameArr.push({
                            label: arr.join('/'),
                        })
                        idsArr.push(j[j.length - 1])
                    })
                }
                that.selectedcatArr = nameArr;
                that.goodsDetail.category_ids = idsArr.join(',');
            },
            closeTag(val) {
                this.timeData.category_ids_arr.splice(val, 1);
                this.selectedcatArr.splice(val, 1)
                let idsArr = []
                this.timeData.category_ids_arr.forEach(j => {
                    idsArr.push(j[j.length - 1])
                })
                this.goodsDetail.category_ids = idsArr.join(',');
                this.panelChange(this.timeData.category_ids_arr)
                this.$forceUpdate()
            },
            createTemplate(type) {
                let that = this;
                if (type == 'service') {
                    Fast.api.open("shopro/goods/service/add", "新建");
                } else {
                    Fast.api.open("shopro/dispatch/" + type + "/add", "新建", {
                        callback(data) {
                            if (data.data) {
                                that.getDispatchTemplateData(type, 'create'); //TODO 判断type
                            }
                        }
                    });
                }
            },
            getInit(skuList, skuPrice) {
                // 记录每个规格项真实 id，对应的临时 id
                let tempIdArr = {};
                for (let i in skuList) {
                    // 为每个 规格增加当前页面自增计数器，比较唯一用
                    skuList[i]['temp_id'] = this.countId++
                    for (let j in skuList[i]['children']) {
                        // 为每个 规格项增加当前页面自增计数器，比较唯一用
                        skuList[i]['children'][j]['temp_id'] = this.countId++

                        // 记录规格项真实 id 对应的 临时 id
                        tempIdArr[skuList[i]['children'][j]['id']] = skuList[i]['children'][j]['temp_id']
                    }
                }
                // for (let i in skuPrice) {
                for (var i = 0; i < skuPrice.length; i++) {
                    let tempSkuPrice = skuPrice[i]
                    tempSkuPrice['temp_id'] = i + 1

                    // 将真实 id 数组，循环，找到对应的临时 id 组合成数组
                    tempSkuPrice['goods_sku_temp_ids'] = [];
                    let goods_sku_id_arr = tempSkuPrice['goods_sku_ids'].split(',');
                    for (let ids of goods_sku_id_arr) {
                        tempSkuPrice['goods_sku_temp_ids'].push(tempIdArr[ids])
                    }

                    skuPrice[i] = tempSkuPrice
                }
                if (this.type == 'copy') {
                    for (let i in skuList) {
                        // 为每个 规格增加当前页面自增计数器，比较唯一用
                        skuList[i].id = 0;
                        for (let j in skuList[i]['children']) {
                            skuList[i]['children'][j].id = 0;
                        }
                    }
                }

                this.skuList = skuList;
                this.skuPrice = skuPrice;

                setTimeout(() => {
                    // 延迟触发更新下面列表
                    this.isEditInit = true;
                }, 200)
            },
            getEditData() {
                let that = this;
                Fast.api.ajax({
                    url: 'shopro/goods/goods/detail/ids/' + that.editId,
                    loading: true,
                }, function (ret, res) {
                    Controller.api.bindevent();
                    $('#c-content').html(res.data.detail.content)
                    for (key in that.goodsDetail) {
                        if (res.data.detail[key]) {
                            that.goodsDetail[key] = res.data.detail[key]
                        } else {
                            that.goodsDetail.express_ids = res.data.detail.dispatch_group_ids_arr.express ? res.data.detail.dispatch_group_ids_arr.express : '';

                            that.goodsDetail.store_ids = res.data.detail.dispatch_group_ids_arr.store ? res.data.detail.dispatch_group_ids_arr.store : '';

                            that.goodsDetail.selfetch_ids = res.data.detail.dispatch_group_ids_arr.selfetch ? res.data.detail.dispatch_group_ids_arr.selfetch : '';

                            that.goodsDetail.autosend_ids = res.data.detail.dispatch_group_ids_arr.autosend ? res.data.detail.dispatch_group_ids_arr.autosend : '';
                        }
                    }
                    for (key in that.timeData) {
                        if (res.data.detail[key]) {
                            that.timeData[key] = res.data.detail[key]
                        }

                    }
                    let activeId = ''
                    that.timeData.category_ids_arr.forEach(i => {
                        activeId = i[0];
                        i.splice(0, 1)
                    })
                    if (that.categoryOptions.length > 0) {
                        that.categoryOptions.forEach((j, index) => {
                            if (j.id == activeId) {
                                that.activeName = j.name;
                                that.activeIndex = index;
                            }
                        })
                    }
                    let nameArr = [];
                    that.selectedcatArr = []
                    if (that.timeData.category_ids_arr.length > 0) {
                        that.timeData.category_ids_arr.forEach(j => {
                            let arr = []
                            if (j.length == 1) {
                                that.categoryOptions[that.activeIndex].children.forEach(c => {
                                    if (c.id == j[0]) {
                                        arr.push(c.name)
                                    }
                                })
                            } else if (j.length == 2) {
                                that.categoryOptions[that.activeIndex].children.forEach(c => {
                                    if (c.id == j[0]) {
                                        arr.push(c.name)
                                        c.children.forEach(a => {
                                            if (a.id == j[1]) {
                                                arr.push(a.name)
                                            }
                                        })
                                    }
                                })
                            } else if (j.length == 3) {
                                that.categoryOptions[that.activeIndex].children.forEach(c => {
                                    if (c.id == j[0]) {
                                        arr.push(c.name)
                                        c.children.forEach(a => {
                                            if (a.id == j[1]) {
                                                arr.push(a.name)
                                                a.children.forEach(t => {
                                                    if (t.id == j[2]) {
                                                        arr.push(t.name)
                                                    }
                                                })
                                            }
                                        })
                                    }
                                })
                            }

                            nameArr.push({
                                label: arr.join('/'),
                            })
                        })
                    }
                    that.selectedcatArr = nameArr;

                    that.timeData.dispatch_type_arr.forEach(i => {
                        that.getDispatchTemplateData(i, 'edit');
                    })
                    that.getInit(res.data.skuList, res.data.skuPrice);
                    return false;
                })
            },
            submitForm(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        let that = this;
                        let arrForm = JSON.parse(JSON.stringify(that.goodsDetail));
                        let params_arrflg = true;
                        arrForm.params_arr.forEach(i => {
                            for (key in i) {
                                if (!i[key]) {
                                    params_arrflg = false;
                                }
                            }
                        })
                        if (!params_arrflg) {
                            Toastr.error('参数详情未填写完整');
                            return false;
                        }
                        arrForm.params = JSON.stringify(arrForm.params_arr);
                        arrForm.content = $("#c-content").val();

                        var arrids = []
                        // 发货模板id
                        if (arrForm.type == 'normal') {
                            if (arrForm.dispatch_type.indexOf('express') != -1 && arrForm.express_ids != '') {
                                arrids.push(arrForm.express_ids);
                            }
                            if (arrForm.dispatch_type.indexOf('store') != -1 && arrForm.store_ids != '') {
                                arrids.push(arrForm.store_ids);
                            }
                            if (arrForm.dispatch_type.indexOf('selfetch') != -1 && arrForm.selfetch_ids != '') {
                                arrids.push(arrForm.selfetch_ids);
                            }
                            arrForm.dispatch_ids = arrids.join(",")
                        } else {
                            if (arrForm.dispatch_type == 'selfetch' && arrForm.selfetch_ids != '') {
                                arrids = []
                                arrids.push(arrForm.selfetch_ids);
                            } else if (arrForm.dispatch_type == 'autosend' && arrForm.autosend_ids != '') {
                                arrids = []
                                arrids.push(arrForm.autosend_ids);
                            }
                        }
                        arrForm.dispatch_ids = arrids.join(",")
                        that.mustDel.forEach(i => {
                            delete arrForm[i]
                        })
                        if (arrForm.is_sku == 0) {
                            that.skuList = [];
                            that.skuPrice = [];
                        }
                        // console.log(arrForm)
                        // return false;
                        if (that.editId && that.type == 'edit') {
                            Fast.api.ajax({
                                url: 'shopro/goods/goods/edit/ids/' + that.editId,
                                loading: true,
                                data: {
                                    row: arrForm,
                                    sku: {
                                        listData: JSON.stringify(that.skuList),
                                        priceData: JSON.stringify(that.skuPrice)
                                    }
                                }
                            }, function (ret, res) {
                                Fast.api.close();
                            })
                        } else {
                            if (this.type == 'copy') {
                                delete arrForm.id
                            }
                            Fast.api.ajax({
                                url: 'shopro/goods/goods/add',
                                loading: true,
                                data: {
                                    row: arrForm,
                                    sku: {
                                        listData: JSON.stringify(that.skuList),
                                        priceData: JSON.stringify(that.skuPrice)
                                    }
                                }
                            }, function (ret, res) {
                                Fast.api.close();
                            })
                        }

                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            resetForm(formName) {
                this.$refs[formName].resetFields();
            },
            addImg(type, index, multiple) {
                let that = this;
                parent.Fast.api.open("general/attachment/select?multiple=" + multiple, "选择图片", {
                    callback: function (data) {
                        switch (type) {
                            case "image":
                                that.goodsDetail.image = data.url;
                                break;
                            case "images":
                                that.goodsDetail.images = that.goodsDetail.images ? that.goodsDetail.images + ',' + data.url : data.url;
                                let arrs = that.goodsDetail.images.split(',');
                                if (arrs.length > 9) {
                                    that.timeData.images_arr = arrs.slice(-9)
                                } else {
                                    that.timeData.images_arr = arrs
                                }
                                that.goodsDetail.images = that.timeData.images_arr.join(',');
                                break;
                            case "sku":
                                that.skuPrice[index].image = data.url;
                                break;
                        }
                    }
                });
                return false;
            },
            delImg(type, index) {
                let that = this;
                switch (type) {
                    case "image":
                        that.goodsDetail.image = '';
                        break;
                    case "images":
                        that.timeData.images_arr.splice(index, 1);
                        that.goodsDetail.images = that.timeData.images_arr.join(",");
                        break;
                    case "sku":
                        that.skuPrice[index].image = '';
                        break;

                }
            },
            changeGoodsType(type) {
                this.goodsDetail.type = type;
                this.goodsDetail.dispatch_ids_arr = [];
                this.goodsDetail.dispatch_ids = '';
                this.goodsDetail.dispatch_type_arr = [];
                this.goodsDetail.dispatch_type = '';
            },
            categoryChange(val) {
                this.goodsDetail.category_ids = val.join(',');
            },
            serviceChange(val) {
                this.goodsDetail.service_ids = val.join(',');
            },
            dispatchTypeChange(val) {
                this.goodsDetail.dispatch_type = val.join(',');
            },
            dispatchTypeChanger(val) {
                this.goodsDetail.dispatch_type = val;
                this.getDispatchTemplateData(val, 'virtual');
            },
            getDispatchTemplateData(type, fristEdit) {
                let that = this;
                if (this.goodsDetail.dispatch_type.indexOf(type) == -1 || fristEdit == 'edit' || fristEdit == 'virtual' || fristEdit == 'create') {
                    Fast.api.ajax({
                        url: 'shopro/dispatch/dispatch/select/type/' + type,
                        loading: false,
                        type: 'GET',
                    }, function (ret, res) {
                        that.$set(that.dispatchOptions, type, res.data)
                        return false;
                    })
                }
            },
            getCategoryOptions(form) {
                let that = this;

                Fast.api.ajax({
                    url: 'shopro/category/index',
                    loading: false,
                }, function (ret, res) {
                    that.categoryOptions = res.data;
                    if (that.categoryOptions.length > 0) {
                        if (that.activeName && that.activeIndex) {

                        } else {
                            that.activeName = that.categoryOptions[0].name
                            that.activeIndex = 0;
                        }
                        that.categoryOptions.forEach(i => {
                            if (i.children && i.children.length > 0) {
                                i.children.forEach(j => {
                                    if (j.children && j.children.length > 0) {
                                        j.children.forEach(k => {
                                            if (k.children && k.children.length > 0) {
                                                k.children.forEach(g => {

                                                })
                                            } else {
                                                delete k.children;
                                            }
                                        })
                                    } else {
                                        delete j.children;
                                    }
                                })
                            } else {
                                delete i.children;
                            }
                        })
                    }
                    if(form){
                        that.getEditData()
                    }
                    return false;
                })
            },
            getDispatchType() {
                let that = this;
                Fast.api.ajax({
                    url: 'shopro/dispatch/dispatch/typeList',
                    loading: false,
                }, function (ret, res) {
                    let arr = []
                    for (key in res.data) {
                        arr.push({
                            id: key,
                            name: res.data[key]
                        })
                    }
                    that.dispatchType = arr;
                    return false;
                })
            },
            getServiceOptions() {
                let that = this;
                Fast.api.ajax({
                    url: 'shopro/goods/service/all',
                    loading: false,
                }, function (ret, res) {
                    that.serviceOptions = res.data
                    return false;
                })
            },
            gotoback(formName) {
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.stepActive++;
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            gonextback() {
                this.stepActive--;
            },
            addParams() {
                this.goodsDetail.params_arr.push({
                    title: '',
                    content: ''
                })
            },
            delParams(index) {
                this.goodsDetail.params_arr.splice(index, 1)
            },

            //添加主规格
            addMainSku() {
                // if (this.skuModal !== '') {
                this.skuList.push({
                    id: 0,
                    temp_id: this.countId++,
                    name: this.skuModal,
                    pid: 0,
                    children: []
                })
                this.skuModal = '';
                // this.skuPrice = []       // 新添加的主规格不清空 skuPrice,当添加主规格第一个子规格的时候清空
                this.buildSkuPriceTable()
                // }
            },
            //添加子规格
            addChildrenSku(k) {
                // if (this.childrenModal[k] !== '') {
                // 检测当前子规格是否已经被添加过了
                let isExist = false
                this.skuList[k].children.forEach(e => {
                    if (e.name == this.childrenModal[k] && e.name != "") {
                        isExist = true
                    }
                })

                if (isExist) {
                    Toastr.error('子规格已存在');
                    return false;
                }

                this.skuList[k].children.push({
                    id: 0,
                    temp_id: this.countId++,
                    name: this.childrenModal[k],
                    pid: this.skuList[k].id,
                })

                this.childrenModal[k] = '';

                // 如果是添加的第一个子规格，清空 skuPrice
                if (this.skuList[k].children.length == 1) {
                    this.skuPrice = [] // 规格大变化，清空skuPrice
                    this.isResetSku = 1; // 重置规格
                }

                this.buildSkuPriceTable()
                // }
            },
            //删除主规格
            deleteMainSku(k) {
                let data = this.skuList[k]

                // 删除主规格
                this.skuList.splice(k, 1)

                // 如果当前删除的主规格存在子规格，则清空 skuPrice， 不存在子规格则不清空
                if (data.children.length > 0) {
                    this.skuPrice = [] // 规格大变化，清空skuPrice
                    this.isResetSku = 1; // 重置规格
                }

                this.buildSkuPriceTable()
            },
            //删除子规格
            deleteChildrenSku(k, i) {
                let data = this.skuList[k].children[i]
                this.skuList[k].children.splice(i, 1)

                // 查询 skuPrice 中包含被删除的的子规格的项，然后移除
                let deleteArr = []
                this.skuPrice.forEach((item, index) => {
                    item.goods_sku_text.forEach((e, i) => {
                        if (e == data.name) {
                            deleteArr.push(index)
                        }
                    })
                })
                deleteArr.sort(function (a, b) {
                    return b - a;
                })
                // 移除有相关子规格的项
                deleteArr.forEach((i, e) => {
                    this.skuPrice.splice(i, 1)
                })

                // 当前规格项，所有子规格都被删除，清空 skuPrice
                if (this.skuList[k].children.length <= 0) {
                    this.skuPrice = [] // 规格大变化，清空skuPrice
                    this.isResetSku = 1; // 重置规格
                }
                this.buildSkuPriceTable()
            },
            editStatus(i) {
                if (this.skuPrice[i].status == 'up') {
                    this.skuPrice[i].status = 'down'
                } else {
                    this.skuPrice[i].status = 'up'
                }

            },
            //组合新的规格价格库存重量编码图片
            buildSkuPriceTable() {
                let arr = [];
                //遍历sku子规格生成新数组，然后执行递归笛卡尔积
                this.skuList.forEach((s1, k1) => {
                    let children = s1.children;
                    let childrenIdArray = [];
                    if (children.length > 0) {
                        children.forEach((s2, k2) => {
                            childrenIdArray.push(s2.temp_id);
                        })

                        // 如果 children 子规格数量为 0,则不渲染当前规格, （相当于没有这个主规格）
                        arr.push(childrenIdArray);
                    }
                })

                this.recursionSku(arr, 0, []);
            },
            //递归找笛卡尔规格集合
            recursionSku(arr, k, temp) {
                if (k == arr.length && k != 0) {
                    let tempDetail = []
                    let tempDetailIds = []

                    temp.forEach((item, index) => {
                        for (let sku of this.skuList) {
                            for (let child of sku.children) {
                                if (item == child.temp_id) {
                                    tempDetail.push(child.name)
                                    tempDetailIds.push(child.temp_id)
                                }
                            }
                        }
                    })

                    let flag = false // 默认添加新的
                    for (let i = 0; i < this.skuPrice.length; i++) {
                        if (this.skuPrice[i].goods_sku_temp_ids.join(',') == tempDetailIds.join(',')) {
                            flag = i
                            break;
                        }
                    }

                    if (flag === false) {
                        this.skuPrice.push({
                            id: 0,
                            temp_id: this.skuPrice.length + 1,
                            goods_sku_ids: '',
                            goods_id: 0,
                            weigh: 0,
                            image: '',
                            stock: 0,
                            price: 0,
                            sn: '',
                            weight: 0,
                            status: 'up',
                            goods_sku_text: tempDetail,
                            goods_sku_temp_ids: tempDetailIds,
                        });
                    } else {
                        this.skuPrice[flag].goods_sku_text = tempDetail
                        this.skuPrice[flag].goods_sku_temp_ids = tempDetailIds
                    }
                    return;
                }
                if (arr.length) {
                    for (let i = 0; i < arr[k].length; i++) {
                        temp[k] = arr[k][i]
                        this.recursionSku(arr, k + 1, temp)
                    }
                }
            },
            allEditData(type, opt) {
                switch (opt) {
                    case 'define':
                        this.skuPrice.forEach(i => {
                            i[type] = this.allEditDatas;
                        })
                        this.allEditDatas = ''
                        this.allEditPopover[type] = false;
                        break;
                    case 'cancel':
                        this.allEditDatas = ''
                        this.allEditPopover[type] = false;
                        break;
                }
            }
        },
        watch: {
            stepActive(newVal) {
                this.editor = null;
            },
            skuList: {
                handler(newName, oldName) {
                    if (this.isEditInit) { // 编辑初始化的时候会修改 skuList 但这时候不触发更新
                        this.buildSkuPriceTable();
                    }
                },
                deep: true
            }
        },
    })
</script>
</html>